package com.dream.core.utils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class URLUtil {

    /**
     * 在url上往后追加参数
     *
     * @param url  连接
     * @param data 参数map
     * @return url
     */
    public static String appendUrl(String url, Map<String, Object> data) {
        String newUrl = url;
        StringBuilder param = new StringBuilder();
        for (String key : data.keySet()) {
            param.append(key).append("=").append(data.get(key).toString()).append("&");
        }
        String paramStr = param.toString();
        paramStr = paramStr.substring(0, paramStr.length() - 1);
        if (newUrl.contains("?")) {
            newUrl += "&" + paramStr;
        } else {
            newUrl += "?" + paramStr;
        }
        return newUrl;
    }

    /**
     * 取出指定的参数
     *
     * @param url   连接
     * @param param 参数
     * @return value
     */
    public static String getParamByUrl(String url, String param) {
        url += "&";
        String pattern = "(\\?|&){1}#{0,1}" + param + "=[a-z|A-Z|0-9|\\-|\\:]*(&{1})";

        Pattern r = Pattern.compile(pattern);

        Matcher m = r.matcher(url);
        if (m.find()) {
            return m.group(0).split("=")[1].replace("&", "");
        } else {
            return null;
        }
    }
}
